package com.foreknow.elm.dao.impl;

import com.foreknow.elm.dao.OrderDetailetDao;
import com.foreknow.elm.po.Food;
import com.foreknow.elm.po.OrderDetailet;
import com.foreknow.elm.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class OrderDetailetDaoImpl implements OrderDetailetDao {
    private Connection con = null;
    private PreparedStatement pst = null;
    private ResultSet rs = null;

    @Override
    public int saveOrderDetailet(Integer orderId,Integer foodId,Integer quantity) throws Exception {
        String sql = "insert into orderdetailet(orderId,foodId,quantity) values(?,?,?)";
        int row;
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            pst.setInt(1,orderId);
            pst.setInt(2,foodId);
            pst.setInt(3,quantity);
            row = pst.executeUpdate();
        }finally {
            DBUtil.close(pst);
        }
        return row;
    }

    @Override
    public List<OrderDetailet> listOrderDetailet(Integer orderId) throws Exception {
        String sql = "select o.*,f.foodName,f.foodPrice from orderdetailet o,food f where o.foodId=f.foodId and orderId=?";
        List<OrderDetailet> list = new ArrayList<>();
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            pst.setInt(1,orderId);
            rs = pst.executeQuery();
            while (rs.next()){
                OrderDetailet od = new OrderDetailet();
                od.setFoodId(rs.getInt("foodId"));
                od.setOdId(rs.getInt("odId"));
                od.setOrderId(rs.getInt("orderId"));
                od.setQuantity(rs.getInt("quantity"));
                Food food = new Food();
                food.setFoodName(rs.getString("foodName"));
                food.setFoodPrice(rs.getDouble("foodPrice"));
                od.setFood(food);
                list.add(od);
            }
        }finally {
            DBUtil.close(rs,pst);
        }
        return list;
    }
}
